package navigation.wzg.com.navigation.activities;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import navigation.wzg.com.navigation.MainActivity;
import navigation.wzg.com.navigation.R;
import navigation.wzg.com.navigation.Soaked.Soaked;
import navigation.wzg.com.navigation.db.Diary;
import navigation.wzg.com.navigation.db.greendao.DiaryDao;
import navigation.wzg.com.navigation.http.UpdateGET;
import navigation.wzg.com.navigation.vo.AFaApplication;

public class Update_diary extends AppCompatActivity {

    @BindView(R.id.uu)
    LinearLayout uu;
    @BindView(R.id.update_button)
    Button updateButton;
    @BindView(R.id.update_toolbar)
    Toolbar updateToolbar;
    @BindView(R.id.update_text)
    EditText updateText;
    @BindView(R.id.activity_update)
    LinearLayout activityUpdate;
    @BindView(R.id.update_time)
    TextView updateTime;

    private Long id;
    private String matter;
    private String time;
    private DiaryDao dao;
    private String date;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);
        ButterKnife.bind(this);
        Soaked.initState(this, uu);
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        date = sDateFormat.format(new Date());

        dao = AFaApplication.getApplication().getDaoSession().getDiaryDao();
        //Toolbar设置
        updateToolbar.setTitle("编辑日记");
        setSupportActionBar(updateToolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        updateToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updatelist();
            }
        });

        //TODO 接收跳转带来的数据
        Bundle bundle = this.getIntent().getExtras();
        id = bundle.getLong("id");
        time = bundle.getString("time");
        matter = bundle.getString("matter");
        updateTime.setText(time);
        String[] aa = new String[0];
        int ss = matter.indexOf("</image>");
        if (ss==1){
            aa = matter.split("</image>");
//            Toast.makeText(this, aa[1], Toast.LENGTH_SHORT).show();
            matter = matter.replace("</image>","");
            matter = matter.replace(aa[1],"");
//            Toast.makeText(this, "!=0", Toast.LENGTH_SHORT).show();
        }
        updateText.setText(matter);
        if (aa.length>=2){
            srcshow(aa[1]);
        }
    }

    /**
     * 监听返回事件
     */
    public void onBackPressed() {
        if (updateText.getText().toString().equals(matter.toString())) {
            updatelist();
        } else {
            new AlertDialog.Builder(this)
                    .setTitle("通知：")
                    .setMessage("检测到你已更改，是否保存")
                    .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            update();
                            updatelist();
                        }
                    }).setNegativeButton("不保存", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    updatelist();
                }
            }).show();
        }

//        overridePendingTransition(R.anim.out, R.anim.up);
    }

    //刷新Listview
    public void updatelist() {
        startActivity(new Intent(Update_diary.this, MainActivity.class));
        finish();
        overridePendingTransition(R.anim.out, R.anim.up);
    }

    @OnClick(R.id.update_button)
    public void onViewClicked() {
        update();
        updatelist();
    }

    public void update() {
        String update_text = updateText.getText().toString();
        String str;
        if (update_text.length() > 15) {
            str = update_text.substring(0, 15);
        } else {
            str = update_text;
        }
        String end;
        if (update_text.length() <= 15) {
            end = "";
        } else {
            end = "...";
        }
        String title = str + end;
        if (update_text.length() == 0) {
            Toast.makeText(this, "请不要保存空的日记", Toast.LENGTH_SHORT).show();
        } else {
            Diary updateData = new Diary(id, date, title, update_text);
            dao.update(updateData);
            Toast.makeText(this, "修改完成", Toast.LENGTH_SHORT).show();
        }
    }


    protected void srcshow(String srcs) {
        Uri uri = Uri.parse(srcs);
//            uri = data.getData();
        ContentResolver cr = Update_diary.this.getContentResolver();
        Bitmap bitmap = null;
        Bundle extras = null;
        //如果是选择照片

            try {
                //将对象存入Bitmap中
                bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        int imgWidth = bitmap.getWidth();
        int imgHeight = bitmap.getHeight();
        double partion = imgWidth * 1.0 / imgHeight;
        double sqrtLength = Math.sqrt(partion * partion + 1);
        //新的缩略图大小
        double newImgW = 480 * (partion / sqrtLength);
        double newImgH = 480 * (1 / sqrtLength);
        float scaleW = (float) (newImgW / imgWidth);
        float scaleH = (float) (newImgH / imgHeight);

        Matrix mx = new Matrix();
        //对原图片进行缩放
        mx.postScale(scaleW, scaleH);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, imgWidth, imgHeight, mx, true);
        final ImageSpan imageSpan = new ImageSpan(this, bitmap);
        SpannableString spannableString = new SpannableString("</image>" + uri + "</image>");
        spannableString.setSpan(imageSpan, 0, spannableString.length(), SpannableString.SPAN_MARK_MARK);
        //光标移到下一行
        updateText.append("\n");
        Editable editable = updateText.getEditableText();
        int selectionIndex = updateText.getSelectionStart();
        spannableString.getSpans(0, spannableString.length(), ImageSpan.class);

        //将图片添加进EditText中
        editable.insert(1, spannableString);
        //添加图片后自动空出两行
        updateText.append("\n\n");
    }
}
